<template>
    <div>
        <el-button type="primary" @click="showFormDialog">新建单</el-button>
        <el-button type="danger" @click="handleDelete">删除</el-button>
        <el-table
            :data="pagedMaintenanceList"
            v-model="selectedRows"
            @selection-change="handleSelectionChange"
            style="width: 100%"
        >
            <el-table-column type="selection"></el-table-column>
            <el-table-column prop="name" label="单名称"></el-table-column>
            <el-table-column
                prop="submitter"
                label="提单人姓名"
            ></el-table-column>
            <el-table-column prop="department" label="部门"></el-table-column>
            <el-table-column
                prop="repairDate"
                label="日期"
            ></el-table-column>
            <el-table-column prop="content" label="内容"></el-table-column>
            <el-table-column prop="phone" label="手机号码"></el-table-column>
            <el-table-column prop="attachments" label="附件">
                <template slot-scope="scope">
                    <div
                        v-for="attachment in scope.row.attachments"
                        :key="attachment"
                    >
                        <img
                            v-if="isImage(attachment)"
                            :src="attachment"
                            alt="Attachment"
                            style="max-width: 100px; max-height: 100px"
                        />
                        <a v-else :href="attachment" target="_blank">
                            {{ getAttachmentName(attachment) }}
                        </a>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            :current-page="currentPage"
            :total="maintenanceList.length"
        />
        <el-dialog
            title="新增单"
            :visible.sync="isFormDialogVisible"
            @close="resetForm"
        >
            <el-form ref="maintenanceForm" :model="form" :rules="rules">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="提单人姓名" prop="submitter">
                    <el-input v-model="form.submitter"></el-input>
                </el-form-item>
                <el-form-item label="部门" prop="department">
                    <el-input v-model="form.department"></el-input>
                </el-form-item>
                <el-form-item label="日期" prop="repairDate">
                    <el-date-picker
                        v-model="form.repairDate"
                        type="date"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <el-input type="textarea" v-model="form.content"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item label="附件">
                    <el-upload
                        :action="uploadAction"
                        :file-list="form.attachments"
                        :on-success="handleUploadSuccess"
                        :on-remove="handleRemoveAttachment"
                        list-type="picture-card"
                        multiple
                    >
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="closeFormDialog">取消</el-button>
                <el-button type="primary" @click="submitForm">提交</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            isFormDialogVisible: false,
            maintenanceList: [], // 列表数据
            isLoading: false,
            selectedRows: [], // 选中的行
            pageSize: 10, // 每页显示的条数
            currentPage: 1, // 当前页码
            form: {
                name: "",
                submitter: "", // 提单人姓名
                department: "", // 部门
                repairDate: null, // 日期
                content: "", // 内容
                phone: "",
                attachments: [], // 附件列表
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: "请输入名称",
                        trigger: "blur",
                    },
                ],
                submitter: [
                    {
                        required: true,
                        message: "请输入提单人姓名",
                        trigger: "blur",
                    },
                ],
                department: [
                    { required: true, message: "请输入部门", trigger: "blur" },
                ],
                repairDate: [
                    {
                        required: true,
                        message: "请选择日期",
                        trigger: "change",
                    },
                ],
                content: [
                    {
                        required: true,
                        message: "请输入内容",
                        trigger: "blur",
                    },
                ],
                phone: [
                    {
                        required: true,
                        message: "请输入手机号码",
                        trigger: "blur",
                    },
                    {
                        pattern: /^1\d{10}$/,
                        message: "手机号码格式不正确",
                        trigger: "blur",
                    },
                ],
            },
        };
    },
    computed: {
        pagedMaintenanceList() {
            const startIndex = (this.currentPage - 1) * this.pageSize;
            const endIndex = startIndex + this.pageSize;
            return this.maintenanceList.slice(startIndex, endIndex);
        },
        uploadAction() {
            // 修改为真实的附件上传接口
            return "/upload";
        },
    },
    methods: {
        handleSizeChange(size) {
            this.pageSize = size;
        },
        handleCurrentChange(page) {
            this.currentPage = page;
        },
        showFormDialog() {
            this.isFormDialogVisible = true;
        },
        handleSelectionChange(selectedRows) {
            console.log(selectedRows);
            this.selectedRows = selectedRows;
        },
        closeFormDialog() {
            this.isFormDialogVisible = false;
        },
        submitForm() {
            this.$refs.maintenanceForm.validate((valid) => {
                if (valid) {
                    // 这里模拟提交成功后将数据添加到列表中，实际开发中需要替换成真实的提交逻辑。
                    setTimeout(() => {
                        this.maintenanceList.push({ ...this.form });
                        this.closeFormDialog();
                        this.resetForm();
                    }, 1000);
                }
            });
        },
        handleUploadSuccess(response, file, fileList) {
            this.form.attachments = fileList;
        },
        handleRemoveAttachment(file, fileList) {
            this.form.attachments = fileList;
        },
        resetForm() {
            this.$refs.maintenanceForm.resetFields();
            this.form = {
                name: "",
                submitter: "",
                department: "",
                repairDate: null,
                content: "",
                phone: "",
                attachments: [],
            };
        },
        handleDelete() {
            if (this.selectedRows.length === 0) {
                this.$message.warning("请选择要删除");
                return;
            }
            this.$confirm("确认删除选中？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    // 实际开发中应该调用后端接口来进行删除操作
                    this.isLoading = true;
                    setTimeout(() => {
                        this.maintenanceList = this.maintenanceList.filter(
                            (item) => !this.selectedRows.includes(item)
                        );
                        this.selectedRows = [];
                        this.isLoading = false;
                        this.$message.success("删除成功");
                    }, 1000);
                })
                .catch(() => {
                    this.$message.info("已取消删除");
                });
        },
        isImage(attachment) {
            // 自行实现判断附件是否为图片的逻辑，返回 true 或 false
            // 示例：
            return /\.(jpeg|jpg|gif|png)$/.test(attachment.toLowerCase());
        },
        getAttachmentName(attachment) {
            // 获取附件名字，示例：从附件路径中截取文件名
            // 示例：
            const index = attachment.lastIndexOf("/");
            return attachment.substring(index + 1);
        },
        fetchData() {
            // 使用 AJAX 请求获取数据，实际开发中应调用后端接口
            // 示例：使用 axios 发起 GET 请求
            // axios.get("/api/maintenanceList")
            //   .then(response => {
            //     this.maintenanceList = response.data;
            //   })
            //   .catch(error => {
            //     console.error("Error fetching data:", error);
            //   });
        },
    },
    mounted() {
        // 在组件加载完成后获取数据
        this.fetchData();
    },
};
</script>
